//
//  OEUserInfoViewController.m
//  OneEightyNine
//
//  Created by Mac on 2019/3/4.
//  Copyright © 2019 stoneobs. All rights reserved.
//

#import "OEUserInfoViewController.h"
#import "STPhotoUrlImageBrowerController.h"
#import "NSBundle+STSystemTool.h"

@interface OEUserInfoViewController ()<STPhotoUrlImageBrowerControllerDelegate>
@property(nonatomic, strong) NSArray                     *dataSouce;/**<  */
@property(nonatomic, weak) STButton                     *iconButton;/**< <##> */
@property(nonatomic, strong) STUrlPhotoModel                     *photoModel;/**<  */

@property(nonatomic, strong) NSDictionary                     *ageGroupDic;/**< 年龄 */
@property(nonatomic, strong) NSDictionary                     *sexGroupDic;/**< 年龄 */
@end

@implementation OEUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configSubView];
    [self fetchDeflutGroupAndAge];

    // Do any additional setup after loading the view.
}
- (void)fetchDeflutGroupAndAge{
    [OEUserDataController sendFetchSexListRequest:^(BOOL success, NSString *errorString, NSDictionary *resp) {
        if (success) {
            self.sexGroupDic = resp;
        }
    }];
    [OEUserDataController sendFetchAgeListRequest:^(BOOL success, NSString *errorString, NSDictionary *resp) {
        if (success) {
            self.ageGroupDic = resp;
        }
    }];
}
#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 110)];
    header.backgroundColor = UIColor.whiteColor;
    self.tableView.backgroundColor = UIColor.whiteColor;
    __weak typeof(self) weakSelf =  self;
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(10, 30, UIScreenWidth - 20, 40)
                                                     text:OESTRING(@"PERSONAL DATA")
                                                textColor:UIColor.blackColor
                                                     font:18
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [header addSubview:titleLable];
    self.tableView.tableHeaderView = header;
    OEUserModel * user = STUserManger.defult.loginedUser;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                     title:nil
                                                titleColor:nil
                                                 titleFont:0
                                              cornerRadius:20
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [buyButton sd_setBackgroundImageWithURL:[NSURL URLWithString:user.thumb] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"80×80默认头像"]];
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedIconButton];
    }];
    self.iconButton = buyButton;
    

    
    
    self.dataSouce = @[
                        [[STTableEasyModel alloc] initWithTextString:OESTRING(@"HEAD PORTRAIT") accessoryView:buyButton],
                        [[STTableEasyModel alloc] initWithTextString:OESTRING(@"NICKNAME") detailString:user.user_name],
                        [[STTableEasyModel alloc] initWithTextString:OESTRING(@"MOBILE NUMBER") detailString:user.mobile],
                        [[STTableEasyModel alloc] initWithTextString:OESTRING(@"AGE GROUP") detailString:user.age],
                        [[STTableEasyModel alloc] initWithTextString:OESTRING(@"SEX") detailString:user.sex],
                       ];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    [cell setSt_tableEasyModel:model];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    if (indexPath.row == 0) {
        [self onSelctedIconButton];
    }
    if (indexPath.row == 1) {
        STTableViewDetailController * detail =
        [[STTableViewDetailController alloc] initWithPlaceholder:OESTRING(@"Please enter nickname")
                                                           title:model.textString
                                                            text:model.detailString
                                                        complete:^(NSString *text, STTableViewDetailController *detailControllerVC) {
                                                            
                                                            if (text.length && ![text isEqualToString:model.detailString]) {
                                                                [OEUserDataController sendChangeValueRequest:text key:@"user_name" hadle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
                                                                    if (success) {
                                                                        model.detailString = text;
                                                                        [self.tableView reloadData];
                                                                    }
                                                                }];

                                                            }
                                                            if (!text.length) {
                                                                [SVProgressHUD showErrorWithStatus:OESTRING(@"Please enter nickname")];
                                                            }
                                                            [self.navigationController popViewControllerAnimated:YES];
                                                            
                                                        }];
        [self.navigationController pushViewController:detail animated:YES];
    }
    if (indexPath.row == 2) {
        STTableViewDetailController * detail =
        [[STTableViewDetailController alloc] initWithPlaceholder:OESTRING(@"Please enter mobie")
                                                           title:model.textString
                                                            text:model.detailString
                                                        complete:^(NSString *text, STTableViewDetailController *detailControllerVC) {
                                                            
                                                            if (text.length && ![text isEqualToString:model.detailString]) {
                                                                [OEUserDataController sendChangeValueRequest:text key:@"new_mobile" hadle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
                                                                    if (success) {
                                                                        model.detailString = text;
                                                                        [self.tableView reloadData];
                                                                    }
                                                                }];
                                                                
                                                            }
                                                            if (!text.length) {
                                                                [SVProgressHUD showErrorWithStatus:OESTRING(@"Please enter nickname")];
                                                            }
                                                            [self.navigationController popViewControllerAnimated:YES];
                                                            
                                                        }];
        [self.navigationController pushViewController:detail animated:YES];
    }
    if (indexPath.row == 3) {
        if (!self.ageGroupDic) {
             [self fetchDeflutGroupAndAge];
            return;
        }
        NSArray * array = self.ageGroupDic.allValues;
        NSArray * indexArray = self.ageGroupDic.allKeys;
        STActionSheet * sheet = [STActionSheet actionSheetWithTitle:OESTRING(@"AGE GROUP") buttonTitles:array cancelTitle:OESTRING(@"CANCLE") handle:^(NSInteger index) {
            if (index == array.count) {
                return ;
            }
            NSString * age = indexArray[index];
            NSString * ageString = array[index];
            [OEUserDataController sendChangeValueRequest:age key:@"age" hadle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
                if (success) {
                    model.detailString = ageString;
                    [self.tableView reloadData];
                }
            }];
        }];
         [sheet show];
    }
    if (indexPath.row == 4) {
        if (!self.sexGroupDic) {
            [self fetchDeflutGroupAndAge];
            return;
        }
        NSArray * array = self.sexGroupDic.allValues;
        NSArray * indexArray = self.sexGroupDic.allKeys;
        STActionSheet * sheet = [STActionSheet actionSheetWithTitle:OESTRING(@"SEX GROUP") buttonTitles:array cancelTitle:OESTRING(@"CANCLE") handle:^(NSInteger index) {
            if (index == array.count) {
                return ;
            }
            NSString * sex = indexArray[index];
            NSString * sexString = array[index];
            [OEUserDataController sendChangeValueRequest:sex key:@"sex" hadle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
                if (success) {
                    model.detailString = sexString;
                    [self.tableView reloadData];
                }
            }];
            
        }];
        [sheet show];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSelctedIconButton{
    NSMutableArray * models = [NSMutableArray new];
    STUrlPhotoModel * model = [STUrlPhotoModel  new];
    model.originImage = self.iconButton.currentBackgroundImage;;
    [models addObject:model];
    self.photoModel = model;
    STPhotoUrlImageBrowerController * vc = [[STPhotoUrlImageBrowerController alloc] initWithArray:models curentIndex:0];
    vc.shouldHideBottomView = YES;
    vc.STPhotoUrlImageBrowerControllerdelegate = self;
    UIViewController * rootVC = [UIApplication sharedApplication].delegate.window.rootViewController;
    [rootVC presentViewController:vc animated:NO completion:nil];
}

#pragma mark --STPhotoUrlImageBrowerControllerDelegate
- (UIView*)STPhotoSystemBrowserControllerDidScrollToIndexpath:(NSIndexPath*)indexPath model:(STUrlPhotoModel*)model{
    return self.iconButton;
}
- (void)rightBarActionFromController:(STPhotoUrlImageBrowerController*)controller currentIndexPath:(NSIndexPath *)curentIndexpath{
    
    NSArray * array = @[@"保存图片",@"拍照",@"从相册"];
    STActionSheet * sheet = [STActionSheet actionSheetWithTitle:@"请选择" buttonTitles:array cancelTitle:@"取消" handle:^(NSInteger index) {
        if (array.count == index) {
            return ;
        }
        NSString * title = array[index];
        if ([title isEqualToString:@"保存图片"]) {
            [PHPhotoLibrary saveImageToAssetsLibrary:self.iconButton.currentBackgroundImage libraryName:NSBundle.st_applictionDisplayName successHandle:^{
                [SVProgressHUD showSuccessWithStatus:@"保存到相册成功"];
            } errorHandle:^(STSaveImageError error) {
                [SVProgressHUD showErrorWithStatus:@"保存失败"];
            }];
        }
        if ([title isEqualToString:@"拍照"]) {
            [controller st_showTakePhotoImagePicker:^(UIImage *image) {
                [OEUserDataController sendChangeHeaderRequest:image handle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
                    if (success) {
                        self.photoModel.originImage = image;
                        
                        [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                        [controller reloadData];
                    }
                }];
                
            }];
        }
        if ([title isEqualToString:@"从相册"]) {
            [controller st_showchosePhotoImagePicker:^(UIImage *image) {
                [OEUserDataController sendChangeHeaderRequest:image handle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
                    if (success) {
                        self.photoModel.originImage = image;
                        
                        [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                        [controller reloadData];
                    }
                }];
            }];
        }
    }];
    [sheet show];

}
@end
